<template>
    <div class="box">
        <header class="header">
            <van-nav-bar title="购物车" left-arrow @click-left="$router.go(-1)" />
        </header>
        <div class="content">
            <!-- {{ cartList }} -->
            <van-empty v-if="cartList.length == 0"
                image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" image-size="80"
                description="购物车空空如也" />

            <van-swipe-cell v-else v-for="item in cartList" :key="item.id">
                <van-card :num="item.count" :price="item.price" :title="item.title" class="goods-card"
                    :thumb="item.image">
                    <!-- card卡片的插槽 -->
                    <template #tag>
                        <van-checkbox v-model="item.checked"></van-checkbox>
                    </template>
                    <template #footer>
                        <van-stepper v-model="item.count" />
                    </template>
                </van-card>
                <!-- 滑动单元格的插槽 -->
                <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" @click="onDelete(item.id)" />
                </template>
            </van-swipe-cell>
        </div>
    </div>
    <footer class="footer">
        <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="$router.push('/order')">
            <van-checkbox v-model="allChecked">全选</van-checkbox>
        </van-submit-bar>
    </footer>
</template>
<script>
import { mapState, mapActions } from 'pinia'
import { useCounterStore } from '@/store/index'
export default {
    computed: {
        ...mapState(useCounterStore, ['cartList', 'totalPrice']),
        allChecked: {
            // get获取：全选按钮的值
            get() {
                if (this.cartList.length == 0) {
                    // 当购物车列表为空，全选按钮是false
                    return false
                } else {
                    // 如果购物车列表都被选中，全选按钮就是true; 只要有一个不被选中，全选按钮就是false
                    return this.cartList.every(item => item.checked) // item.checked == true

                }
            },
            // set设置：根据全选按钮的变化，设置cartList中商品是否选中
            // 当全选按钮勾上的时候，newval就是true,就应该给cartList中商品都选中；
            // 当全选按钮取消勾选的时候，newval就是false,就应该给cartList中商品都取消选中；
            set(newval) {
                this.cartList.forEach(item => item.checked = newval)
            }
        }
    },
    methods: {
        ...mapActions(useCounterStore, ['deleteItem']),
        onDelete(id) {
            this.deleteItem(id)
        }
    }
}
</script>
<style>
.goods-card {
    margin: 0;
    background-color: white;
}

.delete-button {
    height: 100%;
}
</style>
